import React, {Component, PropTypes} from 'react';

import { Form, Input, Button, InputNumber, DatePicker,Row,Col,message, Radio,Modal } from 'antd';
const RangePicker = DatePicker.RangePicker;
const RadioGroup = Radio.Group;

import moment from 'moment';

const FormItem = Form.Item;
const createForm = Form.create;

function disabledDate(current) {
  return current && current.valueOf() < new Date(new Date()-24*60*60*1000).getTime();
}

export class Step0 extends Component {

  state = {
    formValues : this.props.formValues
  }

  constructor (props) {
    super(props);
  }

  componentWillReceiveProps (props) {
    if(this.props.$loki != props.$loki){
      this.getExamDetail(props.$loki);
    }
  }

  componentDidMount () {
    this.getExamDetail(this.props.$loki);
  }

  getExamDetail ($loki) {
    const { examActions } = this.props;
    examActions.getExamDetail({
      $loki
    }).then(data=>{
      // this.props.form.resetFields()
      const dateFormat = 'YYYY-MM-DD';
      // const exam_range = data.info['exam_range'] ? [moment(data.info['exam_range'][0],dateFormat),moment(data.info['exam_range'][1],dateFormat)] : [];

      if(!data.info || !data.info.exam_name){
        return;
      }

      const exam_start_date = data.info['exam_start_date'] ? moment(data.info['exam_start_date'],dateFormat) : '';
      const exam_end_date = data.info['exam_end_date'] ? moment(data.info['exam_end_date'],dateFormat) : '';

      const { exam_name, exam_time, exam_tfng, exam_single, exam_multiple, exam_qetype,ex } = data.info;
      this.props.form.setFieldsValue({
        exam_name,
        exam_time,
        exam_tfng,
        exam_single,
        exam_multiple,
        exam_start_date,
        exam_end_date,
        exam_qetype:exam_qetype||'0'
      });
    })
  }

  /**
   * 提交exam表单
   * @param formdata
   */
  handleExamSubmit (formdata) {
    const {examActions} = this.props;
    const dateFormat = 'YYYY-MM-DD';

    // var range = [formdata['exam_range'][0].format(dateFormat),formdata['exam_range'][1].format(dateFormat)];
    // formdata['exam_range'] = range;

    formdata['exam_start_date'] = formdata['exam_start_date'].format(dateFormat);
    formdata['exam_end_date'] = formdata['exam_end_date'].format(dateFormat);

    if(this.props.$loki > 0){
      examActions.postEditExam(formdata).then(data=>{
        this.props.next();
      }).catch(err=>{
          message.error(err);
      });
    }else{
      examActions.postAddExam(formdata).then(data=>{
        this.props.next();
      }).catch(err=>{
        message.error(err);
      });
    }
  }

  /**
   * 下一步操作
   */
  handleFormOk () {

    this.props.form.validateFields((err, values) => {
      if (!err) {
        let fields = this.props.form.getFieldsValue();
        if(this.props.$loki > 0) fields.$loki = this.props.$loki;
        fields['status'] = 'setting';

        this.handleExamSubmit(fields);

        // fields['exam_tfng']['total'] = parseInt(fields['exam_tfng']['score']) * parseInt(fields['exam_tfng']['num']);
        // fields['exam_single']['total'] = parseInt(fields['exam_single']['score']) * parseInt(fields['exam_single']['num']);
        // fields['exam_multiple']['total'] = parseInt(fields['exam_multiple']['score']) * parseInt(fields['exam_multiple']['num']);
        // var total = fields['exam_tfng']['total'] + fields['exam_single']['total'] + fields['exam_multiple']['total'];
        // if(total == 100){
        //   this.handleExamSubmit(fields);
        // }else{
        //   Modal.confirm({
        //     title: '信息提示',
        //     content: '本次考试总分不是100分,是否继续',
        //     okText: '继续',
        //     cancelText: '取消',
        //     onOk : ()=>{
        //       this.handleExamSubmit(fields);
        //     }
        //   });
        // }

      }else{
        message.error('表单校验失败');
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    return (
      <div className="ant-steps-wraper">

        <div className="steps-content">
          <Form onSubmit={this.handleSubmit} style={{maxWidth:'800px'}}>
            <FormItem
              {...formItemLayout}
              label="考试名称"
              hasFeedback
            >
              {getFieldDecorator('exam_name', {
                rules: [{ required: true, message: '考试名称不能为空!' }],
              })(
                <Input placeholder="请输入考试名称" />
              )}
            </FormItem>

            {/*
            <FormItem
              {...formItemLayout}
              label="考试日期"
              hasFeedback
            >
              {getFieldDecorator('exam_range', {
                rules: [{ required: true, message: '考试日期不能为空!' }],
              })(
                <RangePicker  disabledDate={disabledDate} />
              )}
            </FormItem>*/
            }

            <Row>
              <Col {...formItemLayout.labelCol} className="ant-form-item-label"><label className="ant-form-item-required">考试日期</label></Col>
              <Col {...formItemLayout.wrapperCol}>
                <Row>
                  <Col span={7}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('exam_start_date', {
                        rules: [{ required: true, message: '开始日期不能为空!' }]
                      })(
                        <DatePicker disabledDate={disabledDate} />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={1} className="ant-form-x">-</Col>
                  <Col span={7}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('exam_end_date', {
                        rules: [{ required: true, message: '结束日期不能为空!' }]
                      })(
                        <DatePicker disabledDate={disabledDate} />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            </Row>

            {/*
            <FormItem
              {...formItemLayout}
              label="考题类型"
            >
              {getFieldDecorator('exam_qetype',{
                rules: [{ required: true, message: '考题类型不能为空!' }]
              })(
                <RadioGroup>
                  <Radio value="0">题目相同</Radio>
                  <Radio value="1">题目不同</Radio>
                </RadioGroup>
              )}
            </FormItem>

            <Row>
              <Col {...formItemLayout.labelCol} className="ant-form-item-label"><label className="ant-form-item-required">判断题</label></Col>
              <Col {...formItemLayout.wrapperCol}>
                <Row>
                  <Col span={7}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('exam_tfng.num', {
                        rules: [{ required: true, message: '数量不能为空!' }]
                      })(
                        <Input placeholder="数量" addonBefore="数量" />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={1} className="ant-form-x">x</Col>
                  <Col span={7}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('exam_tfng.score', {
                        rules: [{ required: true, message: '分值不能为空!' }]
                      })(
                        <Input placeholder="分值" addonBefore="分值"  />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            </Row>

            <Row>
              <Col {...formItemLayout.labelCol} className="ant-form-item-label"><label className="ant-form-item-required">单选题</label></Col>
              <Col {...formItemLayout.wrapperCol}>
                <Row>
                  <Col span={7}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('exam_single.num', {
                        rules: [{ required: true, message: '数量不能为空!' }]
                      })(
                        <Input placeholder="数量" addonBefore="数量" />

                      )}
                    </FormItem>
                  </Col>
                  <Col span={1} className="ant-form-x">x</Col>
                  <Col span={7}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('exam_single.score', {
                        rules: [{ required: true, message: '分值不能为空!' }]
                      })(
                        <Input placeholder="分值" addonBefore="分值" />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            </Row>

            <Row>
              <Col {...formItemLayout.labelCol}  className="ant-form-item-label"><label className="ant-form-item-required">多选题</label></Col>
              <Col {...formItemLayout.wrapperCol}>
                <Row>
                  <Col span={7}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('exam_multiple.num', {
                        rules: [{ required: true, message: '数量不能为空!' }]
                      })(
                        <Input placeholder="数量" addonBefore="数量" />

                      )}
                    </FormItem>
                  </Col>
                  <Col span={1} className="ant-form-x">x</Col>
                  <Col span={7}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('exam_multiple.score', {
                        rules: [{ required: true, message: '分值不能为空!' }]
                      })(
                        <Input placeholder="分值" addonBefore="分值" />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            </Row>*/}


          </Form>
         </div>
        <div className="steps-action">
          <Button type="primary" className="ant-next-btn" onClick={() => this.handleFormOk()}>下一步</Button>
          <Button className="ant-previous-btn" onClick={() => this.props.router.push({pathname:'/examlist'})}>
            返回考试列表
          </Button>
        </div>

      </div>
    )
  }

}

/**
 * 格式化prop {key:{value:string}}
 * @param props
 * @returns {{}}
 */
function formatProps(props) {
  var ret = {};
  for(var i in props){
    ret[i] = {
      value : props[i]
    }
  }
  return ret;
}

export default createForm()(Step0);